<template>
  <div>
    <el-tree
      :data="data"
      show-checkbox
      node-key="id"
      :props="{
        children: 'children',
        label: 'name',
      }"
      :default-expanded-keys="[2, 3]"
      :default-checked-keys="[5]"
    >
    </el-tree>
  </div>
</template>

<script>
var arr = [
  { id: 1, pid: 0, name: "中国" },
  { id: 2, pid: 1, name: "湖北省" },
  { id: 3, pid: 2, name: "武汉市" },
  { id: 4, pid: 2, name: "恩施州" },
  { id: 5, pid: 1, name: "四川省" },
  { id: 6, pid: 0, name: "中国1" },
  { id: 7, pid: 0, name: "中国12" },
  { id: 8, pid: 0, name: "中国134" },
];
function tree(object, parent) {
  let treeList = [];

  object.map((res, index) => {
    if (res.pid === parent) {
      // 第一次循环表示有多少符合条件的一级
      let obj = res; // 拿到符合条件 对象
      let temp;
      temp = tree(object, obj.id); // 拿到父级的id 递归 对比pid
      // 比如 拿到id为1 进入递归 对比 res.pid === 1 拿到结果
      if (temp.length > 0) {
        // 查询有结果 就 赋值
        obj.children = temp;
      }
      treeList.push(obj);
    }
  });
  return treeList;
}
var arr1 = tree(arr, 0);
export default {
  data() {
    return {
      data: arr1,
    };
  },
};
</script>

<style></style>
